import { defineStore } from 'pinia'
import request from '@/utils/request'
import { ApiRes } from '@/types/data'
import { CartItem } from '@/types/cart'
import Confirm from '@/components/confirm'
import useStore from '..'


export default defineStore('cart', {
  persist: true,
  state() {
      return {
        list: [] as CartItem[]
      }
  },
  actions: {
    async addCart(data: CartItem) {
      if (this.isLogin) {
        // 添加购物车
        await request.post('/member/cart', {
          skuId: data.skuId,
          count: data.count
        })
        // 重新获取最新的购物车列表
        this.getCartList()
      } else {
        const sku = this.list.find(item => item.skuId === data.skuId)
        if (sku) {
          sku.count += data.count
        } else {
          this.list.unshift(data)
        }
      }
    },
    async getCartList() {
      if (this.isLogin) {
        const res = await request.get<ApiRes<CartItem[]>>('/member/cart')
        // console.log(res);
        this.list = res.data.result
      }else{
        this.list.forEach(async (cartItem) => {
          const { skuId } = cartItem
          // 根据 skuId 获取最新商品信息
          const res = await request.get<ApiRes<CartItem>>(
            `/goods/stock/${skuId}`
          )
          // 保存最新商品信息
          const lastCartInfo = res.data.result
          // 更新商品现价
          cartItem.nowPrice = lastCartInfo.nowPrice
          // 更新商品库存
          cartItem.stock = lastCartInfo.stock
          // 更新商品是否有效
          cartItem.isEffective = lastCartInfo.isEffective
        })
      }
    },
    async deleteCart(skuIds: string[]) {
      await Confirm({
        title: '温馨提示',
        text: '你确定要删除吗'
      })
      if(this.isLogin) {
        await request.delete('/member/cart', {
          data: {
            ids: skuIds
          }
        })
        this.getCartList()
      }else {
        this.list = this.list.filter((item) => !skuIds.includes(item.skuId))
      }
    },
    async updateCart(skuId: string, data: { selected?: boolean; count?: number }) {
      if(this.isLogin) {
        await request.put(`/member/cart/${skuId}`, data)
        // 重新获取最新购物车列表
        this.getCartList()
      }else{
        const sku = this.effectiveList.find((item) => item.skuId === skuId)
        if (data.selected !== undefined) {
          sku!.selected = data.selected
        }
        if (data.count !== undefined) {
          sku!.count = data.count
        }
      }
    },
    async updateCartAllSelected(selected: boolean) {
      if(this.isLogin) {
        await request.put('/member/cart/selected', {
          selected
        })
        // 重新获取购物车数据
        this.getCartList()
      }else{
        this.list.forEach((item) => {item.selected = selected})
      }
    },
    clearCart() {
      this.list = []
    },
    async mergeLocalCart() {
      const data = this.list.map(({ skuId, selected, count }) => ({
        skuId,
        selected,
        count
      }))
      await request.post('/member/cart/merge', data)
      // 合并成功，重新获取购物车列表
      this.getCartList()
    }
  },
  getters: {
    isLogin(): boolean {
      const { user } = useStore()
      return !!user.profile.token
    },
    effectiveList(): CartItem[] {
      return this.list.filter(item => item.isEffective)
    },
    effectiveCount(): number {
      return this.list.reduce((sum, item) => sum += item.count, 0)
    },
    effectivePrice(): string {
      return this.list.reduce((sum, item) => sum += +item.price * item.count, 0).toFixed(2)
    },
    isAllSelected(): boolean {
      return this.effectiveList.length > 0 && this.effectiveList.every(item => item.selected)
    },
    // 筛选出所有已选中的有效商品
    selectedList(): CartItem[] {
      return this.effectiveList.filter(item => item.selected)
    },
    // 所有选中的商品数量求和
    selectedCounts(): number {
      return this.selectedList.reduce((sum, item) => sum += item.count, 0)
    },
    // 所有选中的商品总价求和
    selectedPrice(): string {
      return this.selectedList.reduce((sum, item) => sum += +item.nowPrice * item.count, 0).toFixed(2)
    }
  }
})